$(function () {
  //$("#questionNameDetail").html("<"+
  //    getCookie("nameOfQuestionnaire") + ">答题情况明细");
  //var oTable = new TableInit();
  //oTable.Init();

  //传回用户名
  var da = {
    "user": getCookie("userName")
  };
  //添加下拉选择问卷
  var selectContent = ''; //下拉选择内容
  jQuery.ajax({
    type: "POST",
    url: httpRequestUrl + "/queryAllQuestionnaireByCreated",
    data: JSON.stringify(da),
    dataType: 'json',
    contentType: "application/json",
    success: function (result) {
      for (var i = 0; i < result.data.length; i++) {
        selectContent += '<option value="' + result.data[i].id + '">' +
            result.data[i].questionName + '</option>'
      }
      $("#ddlActivitynew").html(selectContent)
      $("#ddlActivitynew option[value='" + getCookie("questionId") + "']").attr(
          "selected", "selected");
    }
  });
  //获得答题数据
  getAnswerStatistics();
});

//    切换问卷
$("#ddlActivitynew").change(function () {
  var activity = $(this).val();
  var nameQuestion = $(this)[0].selectedOptions[0].innerHTML;
  if (activity) {
    deleteCookie("questionId");
    setCookie("questionId", activity)
    deleteCookie("nameOfQuestionnaire");
    setCookie("nameOfQuestionnaire", nameQuestion)
    getAnswerStatistics();

  }
})

//根据问卷id获取问卷题目标题和问题类型
function getQuestionTitleList(answerStatistics) {
  //清除数据
  $("#panel-questionTiTle").empty();
  var data = {
    "questionId": getCookie("questionId")
  }
  commonAjaxPost(true, '/queryQuestionnaireQuestionTitle', data,
      function (result) {
        if (result.code === "666") {
          //处理数据
          var questionAnswerList = null;
          if (answerStatistics !== "") {
            questionAnswerList = answerStatistics.data;
          }
          console.log(questionAnswerList);
          var allInfo = result.data;
          if (allInfo === null) {
            return;
          } else {
            var titleContent = '';
            var questionInfoStr = allInfo.question;
            var questionInfo = JSON.parse(questionInfoStr);
            console.log(questionInfo);
            for (var k = 0; k < questionInfo.length; k++) {
              var questionInfoDetail = questionInfo[k];
              var questionType = questionInfoDetail.questionType;
              var questionTitle = questionInfoDetail.questionTitle;
              //questionType 问题类型 0：单选题 1：多选题 2：填空题 3：矩阵量表题 4：量表题
              var questionTypeName = "";
              if (questionType === "0") {
                questionTypeName = "单选题";
              } else if (questionType === "1") {
                questionTypeName = "多选题";
              } else if (questionType === "2") {
                questionTypeName = "填空题";
              } else if (questionType === "3") {
                questionTypeName = "矩阵量表题";
              } else if (questionType === "4") {
                questionTypeName = "量表题";
              } else {
                questionTypeName = "未知";
              }
              //向panel-questionTiTle里面添加题目标题
              titleContent += "    <div id=\"divFilter_" + k
                  + "\" className=\"mrbg\">"
              titleContent += "        <div className=\"playSet\">"
              titleContent += "            <div className=\"head clearfix\">"
              titleContent += "               <div className=\"htit pull-left\">"
              titleContent += "                    <i></i><span style=\"cursor:pointer;font-weight:bold;font-size:16px\""
              titleContent += "                                 id=\"questionTitleDetail_"
                  + k + "\">第" + (k + 1) + "题：" + questionTitle
                  + "</span>&nbsp;"
              titleContent += "                 <i></i> <span style=\"cursor:pointer;font-size:14px;color:grey;\" id=\"questionTypeDetail_"
                  + k + "\">[" + questionTypeName + "]</span>"
              titleContent += "                </div>"
              titleContent += "            </div>"
              titleContent += "       </div>"
              titleContent += "    </div>"
              var questionOption = questionInfoDetail.questionOption;
              //每道题的统计表格
              titleContent += "<div id=\"divSumData" + k
                  + "\"className=\"the-end\" style=\"width:766px;margin:0 auto\"> "
              titleContent += "    <div style=\"clear: both;\"></div>"
              titleContent += "     <div id=\"ctl02_ContentPlaceHolder1_divStatData"
                  + k + "\">"
              titleContent += "        <div className=\"title-item\">"
              titleContent += "            <div style=\"margin:10px auto;titleContent-align:center;\""
              titleContent += "                className=\"Picsetting\">"
              titleContent += "               <table id=\"answerTable_" + k
                  + "\" class=\"table table-bordered table-striped\">"

              //根据问题类型，添加表格表头（不知道为啥，answerTable_k就是传不进去，只能放在这了）
              //getAnswerDetail(k, questionType, questionOption);
              if (questionType === "3") {//矩阵量表题
                //添加数据
                titleContent += "<thead>"
                titleContent += "<tr>"
                titleContent += "    <th style=\"text-align: center\">题目/选项</th>"
                for (var l = 0; l < questionOption.length; l++) {
                  var optionName = questionOption[l].optionWord;
                  if (optionName === null || optionName === '') {
                  } else {
                    titleContent += "    <th style=\"text-align: center\">"
                        + optionName + "</th>"
                  }
                }
                //titleContent += "    <th style=\"text-align: center\">平均分</th>"
                titleContent += "</tr>"
                titleContent += "</thead>"
                titleContent += "<tbody id=\"JuzhenData_" + k + "\">"

                //记录选项个数
                var optionNum = 0;
                for (var q = 0; q < questionOption.length; q++) {
                  var optionWord2 = questionOption[q].optionWord;
                  if (optionWord2 === null || optionWord2 === '') {
                  } else {
                    optionNum++;
                  }
                }

                //向矩阵量表题的表格里面添加数据（不知道为啥，JuzhenData_k就是传不进去，只能放在这了）
                //getJuzhenAnswerCount(k, questionOption);
                //创建小计数组，并初始化
                var totalArr = new Array(optionNum);
                for (var total = 0; total < optionNum; total++) {
                  totalArr[total] = 0;
                }
                //遍历表格每行
                for (var i = 0; i < questionOption.length; i++) {
                  if (questionOption[i].lineTitle !== "") {
                    //创建每行的计数数组并初始化
                    var countArr = new Array(optionNum);
                    for (var j = 0; j < countArr.length; j++) {
                      countArr[j] = 0;
                    }
                    titleContent += "<tr>";
                    var lineTitle = questionOption[i].lineTitle;
                    titleContent += "<td style=\"text-align: center\">"
                        + lineTitle + "</td>";

                    if (questionAnswerList === null) {
                      for (var c = 0; c < optionNum; c++) {
                        titleContent += "<td style=\"text-align: center\">-</td>";
                      }
                    } else {
                      for (var p = 0; p < questionAnswerList.length; p++) {
                        var questionAnswerStr = questionAnswerList[p].questionAnswer;
                        var questionAnswer = questionAnswerStr.match(
                            /\[(.*?)\]/)[1];
                        var questionAnswerArr = questionAnswer.split(",");
                        //取得第k道题的答案
                        var answer = questionAnswerArr[k];
                        //如果有&，用&分割答案
                        var answerArr = answer.split("&");
                        //取得第i行的答案
                        var answerLine = answerArr[i];
                        //第answerLine个选项的计数加1，其余为0
                        for (var n = 0; n < optionNum; n++) {
                          if (n === parseInt(answerLine)) {
                            countArr[n] += 1;
                          } else {
                            countArr[n] += 0;
                          }
                        }
                      }
                      //console.log(countArr);
                      //totalArr数组加上countArr数组
                      for (var kp = 0; kp < optionNum; kp++) {
                        totalArr[kp] += countArr[kp];
                      }
                      for (var o = 0; o < countArr.length; o++) {
                        titleContent += "<td style=\"text-align: center\">"
                            + countArr[o] + "</td>";
                      }
                    }
                    titleContent += "</tr>";
                  }
                }//getJuzhenAnswerCount函数结束
                //添加小计
                titleContent += "<tr>";
                titleContent += "<td style=\"text-align: center\"><b>小计</b></td>";
                for (var total2 = 0; total2 < totalArr.length; total2++) {
                  titleContent += "<td style=\"text-align: center\">"
                      + totalArr[total2] + "</td>";
                }
                for (var m = 0; m < optionNum; m++) {
                  var sumArr = new Array(optionNum);
                  for (var n = 0; n < sumArr.length; n++) {

                  }
                }
                titleContent += "</tbody>"
              } else if (questionType === "2") {//填空题
                //添加表头：序号、作答时间、答案文本
                titleContent += "<thead>"
                titleContent += "<tr>"
                titleContent += "    <th style=\"text-align: center;width: 60px\"><b>序号</b></th>"
                titleContent += "    <th style=\"text-align: center;width: 200px\"><b>答卷提交时间</b></th>"
                titleContent += "    <th style=\"text-align: center\"><b>答案文本</b></th>"
                titleContent += "</tr>"
                titleContent += "</thead>"
                //添加数据
                titleContent += "<tbody id=\"JuzhenData_" + k + "\">"
                //遍历表格每行
                if (questionAnswerList === null) {
                  //显示无数据
                  titleContent += "<tr>";
                  titleContent += "<td style=\"text-align: center\" colspan=\"3\">无数据</td>";
                  titleContent += "</tr>";
                } else {
                  for (var i = 0; i < questionAnswerList.length; i++) {
                    titleContent += "<tr>";
                    titleContent += "<td style=\"text-align: center\">"
                        + (i + 1) + "</td>";
                    titleContent += "<td style=\"text-align: center\">"
                        + questionAnswerList[i].endTime + "</td>";
                    //questionAnswerList[i].questionAnswer
                    var questionAnswerStr = questionAnswerList[i].questionAnswer;
                    var questionAnswer = questionAnswerStr.match(
                        /\[(.*?)\]/)[1];
                    var questionAnswerArr = questionAnswer.split(",");
                    //取得第k道题的答案
                    var answer = questionAnswerArr[k];
                    titleContent += "<td style=\"text-align: center\">"
                        + answer + "</td>";
                    titleContent += "</tr>";
                  }
                }
              } else if (questionType === "0" || questionType === "1"
                  || questionType === "4") {// 单选/多选/量表
                //添加数据
                titleContent += "<thead>"
                titleContent += "<tr>"
                titleContent += "    <th style=\"text-align: center;width: 250px\"><b>选项</b></th>"
                titleContent += "    <th style=\"text-align: center\"><b>小计</b></th>"
                titleContent += "    <th style=\"text-align: center\"><b>比例</b></th>"
                titleContent += "</tr>"
                titleContent += "</thead>"

                titleContent += "<tbody id=\"JuzhenData_" + k + "\">"

                var optionNUM = questionOption.length;
                //向矩阵量表题的表格里面添加数据（不知道为啥，JuzhenData_k就是传不进去，只能放在这了）
                //getJuzhenAnswerCount(k, questionOption);

                if (questionType === "4") {//量表特殊处理
                  for (var i = 0; i < optionNUM; i++) {
                    titleContent += "<tr>";
                    titleContent += "<td style=\"text-align: center\">"
                        + questionOption[i].optionWord + "</td>";
                    //如果是第一个选项或者最后一个选项，就直接填入2个-
                    if (i === 0 || i === optionNUM - 1) {
                      titleContent += "<td style=\"text-align: center\">"
                          + "-" + "</td>";
                      titleContent += "<td style=\"text-align: center\" >"
                          + "-" + "</td>";
                    } else {
                      //创建每行的计数并初始化
                      var countNum = 0;
                      if (questionAnswerList === null) {
                        titleContent += "<td style=\"text-align: center\">-</td>";
                        titleContent += "<td style=\"text-align: center\">-</td>";
                      } else {
                        for (var p = 0; p < questionAnswerList.length; p++) {
                          var questionAnswerStr2 = questionAnswerList[p].questionAnswer;
                          var questionAnswer2 = questionAnswerStr2.match(
                              /\[(.*?)\]/)[1];
                          var questionAnswerArr2 = questionAnswer2.split(",");
                          //取得第k道题的答案
                          var answer2 = questionAnswerArr2[k];
                          //没有&，直接取得答案
                          if ((i + 1) === parseInt(answer2)) {
                            countNum += 1;
                          }
                        }
                        titleContent += "<td style=\"text-align: center\">"
                            + countNum + "</td>";
                        //根据百分比生成进度条
                        var percent = (countNum / questionAnswerList.length)
                            * 100;
                        //如果百分比为0，进度条为0,修改字体颜色,字体在进度条中间显示
                        if (percent === 0) {
                          titleContent += "<td style=\"text-align: center\">"
                              + "<div class=\"progress\" style=\"margin-bottom: 0px\">"
                              + "<div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: 0%;color: #000000\">"
                              + percent.toFixed(2) + "%"
                              + "</div>"
                              + "</div>"
                              + "</td>";
                        } else {
                          titleContent += "<td style=\"text-align: center\">"
                              + "<div class=\"progress\" style=\"margin-bottom: 0px\">"
                              + "<div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: "
                              + percent + "%\">"
                              + percent.toFixed(2) + "%"
                              + "</div>"
                              + "</div>"
                              + "</td>";
                        }
                      }
                    }
                    titleContent += "</tr>";
                  }

                } else {
                  //遍历表格每行
                  for (var i = 0; i < optionNUM; i++) {
                    //创建每行的计数并初始化
                    var countNum = 0;
                    titleContent += "<tr>";
                    titleContent += "<td style=\"text-align: center\">"
                        + (i + 1) + "</td>";
                    if (questionAnswerList === null) {
                      titleContent += "<td style=\"text-align: center\">-</td>";
                      titleContent += "<td style=\"text-align: center\">-</td>";
                    } else {
                      for (var p = 0; p < questionAnswerList.length; p++) {
                        var questionAnswerStr2 = questionAnswerList[p].questionAnswer;
                        var questionAnswer2 = questionAnswerStr2.match(
                            /\[(.*?)\]/)[1];
                        var questionAnswerArr2 = questionAnswer2.split(",");
                        //取得第k道题的答案
                        var answer2 = questionAnswerArr2[k];
                        //如果有&，用&分割答案
                        if (answer2 === null) {
                          continue;
                        } else {
                          if (answer2.indexOf("&") !== -1) {
                            var answerArr2 = answer2.split("&");
                            for (var qk = 0; qk < answerArr2.length; qk++) {
                              if (i === parseInt(answerArr2[qk])) {
                                countNum += 1;
                              } else {
                                countNum += 0;
                              }
                            }
                          } else {
                            //如果没有&，直接取得答案
                            if (i === parseInt(answer2)) {
                              countNum += 1;
                            }
                          }
                        }
                      }
                      titleContent += "<td style=\"text-align: center\">"
                          + countNum + "</td>";
                      //根据百分比生成进度条
                      var percent = (countNum / questionAnswerList.length)
                          * 100;
                      //如果百分比为0，进度条为0,修改字体颜色,字体在进度条中间显示
                      if (percent === 0) {
                        titleContent += "<td style=\"text-align: center\">"
                            + "<div class=\"progress\" style=\"margin-bottom: 0px\">"
                            + "<div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: 0%;color: #000000\">"
                            + percent.toFixed(2) + "%"
                            + "</div>"
                            + "</div>"
                            + "</td>";
                      } else {
                        titleContent += "<td style=\"text-align: center\">"
                            + "<div class=\"progress\" style=\"margin-bottom: 0px\">"
                            + "<div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: "
                            + percent + "%\">"
                            + percent.toFixed(2) + "%"
                            + "</div>"
                            + "</div>"
                            + "</td>";
                      }
                    }
                    titleContent += "</tr>";
                  }//getJuzhenAnswerCount函数结束
                }
                //添加小计
                titleContent += "<tr>";
                titleContent += "<td style=\"text-align: center\"><b>本题有效填写人次</b></td>";
                if (questionAnswerList === null) {
                  titleContent += "<td style=\"text-align: center\"><b>0</b></td>";
                } else {
                  titleContent += "<td style=\"text-align: center\"><b>"
                      + questionAnswerList.length + "</b></td>";
                }
                titleContent += "<td style=\"text-align: center\"></td>";
                titleContent += "</tbody>"
              } else {
                layer.msg("第" + (k + 1) + "题题型错误", {icon: 2});
              }//getAnswerDetail函数结束 */

              titleContent += "              </table>"
              titleContent += "               <div style=\"clear:both;\"></div>"
              titleContent += "           </div>"
              titleContent += "        </div>"
              titleContent += "    </div>"
              titleContent += "   <div style=\"padding:10px 0 10px;\">"
              titleContent += "   </div>"
              titleContent += "  <div style=\"clear: both;\">"
              titleContent += "  </div>"
              titleContent += "   <div className=\"divclear\"></div>"
              titleContent += "</div>"
              //初始化 单选/多选/填空
              //getAnswerDetail(k, questionType, questionOption);
            }
          }
          $("#panel-questionTiTle").append(titleContent)
        }
      }
  )
  ;
}

//获得答卷统计数据
function getAnswerStatistics() {
  var data = {
    "questionId": getCookie("questionId")
  };
  jQuery.ajax({
    type: "POST",
    url: httpRequestUrl + "/selectRecordAnswerDetail",
    data: JSON.stringify(data),
    dataType: 'json',
    contentType: "application/json",
    success: function (result) {
      if (result.code === "666") {
        getQuestionTitleList(result);
      } else if (result.code === "20001") {
        console.log(result.data)
        getQuestionTitleList("");
      } else if (result.code === "333") {
        layer.msg(result.message, {icon: 2});
        setTimeout(function () {
          window.location.href = 'login.html';
        }, 1000)
      } else {
        layer.msg(result.message, {icon: 2})
      }
    }
  });
}

//预览问卷
$('#ctl02_hrefView').click(function () {
  window.open('previewQuestionnaire.html?i=' + getCookie("questionId")
      + '&e0Rp=preview');
});

//设计问卷
function designQuestionnaire() {
  var ifDesignQuestionnaire = getCookie("ifDesignQuestionnaire");
  if (ifDesignQuestionnaire == "false") {
    layer.msg("问卷处于运行状态或问卷已发布，不可设计问卷", {icon: 2})
  } else {
    $.cookie("QuestionId", getCookie("questionId"));
    window.open('designQuestionnaire.html')
  }
}

//发送问卷
function ifSendQuestionnaire() {
  var ifSendQuestionnaire = getCookie("ifSendQuestionnaire");
  if (ifSendQuestionnaire == "false") {
    layer.msg("问卷处于未发送或暂停的状态，不可发送问卷", {icon: 2})
  } else {
    $.cookie("QuestionId", getCookie("questionId"));
    window.location.href = 'sendQuestionnaire.html';
  }
}

//预览问卷
$('#ctl02_hrefView').click(function () {
  window.open('previewQuestionnaire.html?i=' + getCookie("questionId")
      + '&e0Rp=preview');
});
//回车事件
$(document).keydown(function (event) {
  if (event.keyCode == 13) {
    getQuestionnaireAboutSchool();
  }
});

//返回主页
function backhome() {
  window.location.href = 'myQuestionnaires.html'
}

//testBigScreen
function testBigScreen() {
  window.location.href = 'echartsTest.html'
}
